﻿using System;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MiniX.API.Filters
{
    /// <summary>
    /// 封装TOKEN类
    /// </summary>
	public class JwtFilter
	{
        /// <summary>
        /// 构造方法
        /// </summary>
		public JwtFilter()
		{

		}

        /// <summary>
        /// 获取TOKEN
        /// </summary>
        /// <param name="member_id">会员ID</param>
        /// <param name="member_account">会员账号</param>
        /// <returns></returns>
		public static string GetToken(string member_id, string member_account)
		{
            var security_key = AppSettingsFilter.GetSetting("Authentication:JwtBearer:SecurityKey");
            var issuer = AppSettingsFilter.GetSetting("Authentication:JwtBearer:Issuer");
            var audience = AppSettingsFilter.GetSetting("Authentication:JwtBearer:Audience");
            var expires_days = AppSettingsFilter.GetSetting("Setting:TokenExpires");

            var claims = new List<Claim> {
                                new Claim(ClaimTypes.NameIdentifier, member_id),
                                new Claim(ClaimTypes.Sid, member_id),
                                new Claim(ClaimTypes.Name, member_account),
                                new Claim(JwtRegisteredClaimNames.AuthTime, DateTime.UtcNow.ToString("o")),
                            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(security_key));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                expires: DateTime.Now.AddDays(Convert.ToInt32(expires_days)),
                signingCredentials: credentials);

            var access_token = new JwtSecurityTokenHandler().WriteToken(token);

            return access_token;
        }
	}
}

